package com.wlstock.funi.runnable;

import android.os.Handler;

import com.wlstock.funi.app.FundApplication;
import com.wlstock.funi.app.FundAsyTask;
import com.wlstock.funi.dao.MyAccountStockDao;
import com.wlstock.funi.dao.PositionDao;
import com.wlstock.funi.dao.SelfFundSetDao;
import com.wlstock.funi.model.OperateModel;
import com.wlstock.funi.model.SelfFundSetModel;
import com.wlstock.funi.utils.CaculateUtils;
import com.wlstock.funi.utils.HttpUtils;
import com.wlstock.funi.utils.IOUtils;
import com.wlstock.funi.utils.LogUtils;
import com.wlstock.funi.utils.NotiIdGenerator;
import com.wlstock.funi.utils.NotiUtils;
import com.wlstock.funi.utils.StockUtils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;

public class OrderSale {
	private static final long DEFAULT_SECONDS = 30;
	private String stkcode;
	private float price;
	private long qty;
	private OperateModel saleModel;
	private String stkName;
	private OrderListener listener;
	private int maxTime;

	public OrderSale(String stkcode,String stkName ,float price, long qty) {
		super();
		maxTime = 4;
		this.stkcode = stkcode;
		this.price = price;
		this.qty = qty;
		this.stkName = stkName;
	}
	
	public  OrderSale(OperateModel saileModel,String stkcode, String stkName ,float price, long qty ) {
		this(stkcode, stkName,price, qty);
		this.saleModel = saileModel;
	}
	
	
	public  void saile(OrderListener oListener){
		if (!StockUtils.isStkValid(stkcode) && price<=0 && qty<100){
			NotiUtils.showSimpleNoti(FundApplication.getInstance(), NotiIdGenerator.generate(stkcode, NotiIdGenerator.GenerFrom.REALTRADE),stkName+ "卖出下单失败", "基本信息出错,请检查程序", 0);
			return;
		}
		this.listener = oListener;
		FundAsyTask<Void, Void, Object> fundAsyTask = new FundAsyTask<>();
		fundAsyTask.backListener = new FundAsyTask.TaskLitener<Void, Object>() {
			@Override
			public Object doInBackground(Void... param) {
				HttpClient client = new DefaultHttpClient();
				try {
					HttpPost buyPost = new HttpPost(
							"https://etrade.cs.ecitic.com/ymtrade/trade/stockAction.do?method=submitOrder");
					HashMap<String, String> parmHash = new HashMap<String, String>();

					parmHash.put("market", StockUtils.parseStkCode2Market(OrderSale.this.stkcode));
					parmHash.put("secuid", StockUtils.parseStkCode2SecuId(OrderSale.this.stkcode));
					parmHash.put("stkcode", OrderSale.this.stkcode);
					parmHash.put("price", String.valueOf(price));
					parmHash.put("qty", String.valueOf(qty));
					parmHash.put("bsflag", "2");
					parmHash.put("bsprop", "0");
					parmHash.put("type", "stock");
					parmHash.put("saleStatus", "0");
					parmHash.put("seat", "");

					List<? extends NameValuePair> params = HttpUtils.getParms(parmHash);
					// Accept:application/json, text/javascript, */*
					// Accept-Encoding:gzip, deflate
					// Accept-Language:zh-CN,zh;q=0.8,en;q=0.6
					// Connection:keep-alive
					// Content-Length:90
					// Content-Type:application/x-www-form-urlencoded
					// Cookie:JSESSIONID=Qk0HWprRL3fNvzrBxrP2hFZD0MmbtwQg4S9Qf1Fncm02QNykd5Lh!-908755652!297676372;
					// ssl=etrade-ssl-1
					// Host:etrade.cs.ecitic.com
					// Origin:https://etrade.cs.ecitic.com
					// Referer:https://etrade.cs.ecitic.com/ymtrade/stock/buy.jsp
					// User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64)
					// AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86
					// Safari/537.36
					// X-Requested-With:XMLHttpRequest
					HttpEntity entity = new UrlEncodedFormEntity(params);
					buyPost.setEntity(entity);
					buyPost.addHeader("Accept","application/json, text/javascript, */*");
					buyPost.addHeader("Accept-Encoding", "gzip, deflate");
					buyPost.addHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
					buyPost.addHeader("Connection", "keep-alive");
					buyPost.addHeader("Content-Type","application/x-www-form-urlencoded");
					buyPost.addHeader("Cookie", FundApplication.cookie);
					buyPost.addHeader("Referer","https://etrade.cs.ecitic.com/ymtrade/stock/buy.jsp");
					buyPost.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36");
					buyPost.addHeader("X-Requested-With", "XMLHttpRequest");

					// HttpResponse buyPostResponse =
					// FundApplication.client.execute(buyPost);

					HttpResponse buyPostResponse = client.execute(buyPost);
					if (buyPostResponse.getStatusLine().getStatusCode() == 200) {
						// {cssweb_type:'success',cssweb_msg:'证券代码（603998）委托下单成功，委托序号为：3'}
						String result = IOUtils.is2Str(buyPostResponse.getEntity().getContent());
						return result;
					}

				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} finally {
					client.getConnectionManager().shutdown();
				}

				return null;
			}
		};

		fundAsyTask.resultListener = new FundAsyTask.TaskResultListener<Object>() {
			@Override
			public void onPostResult(Object o) {
				if (o!=null){
					String result = (String)o;
					LogUtils.i("卖出下单成功"+result);
					try {
						JSONObject obj = new JSONObject(result);
						if (obj.getString("cssweb_type").equals("success")) {
							MyAccountStockDao.getInstance(FundApplication.getInstance()).updateStkQty(stkcode, 0);
							if (saleModel!=null) {
								NotiUtils.showSimpleNoti(FundApplication.getInstance(), NotiIdGenerator.generate(stkcode, NotiIdGenerator.GenerFrom.REALTRADE), stkName+"卖出下单成功"+" 价格:"+price+" 数量:"+qty + "排名:"+saleModel.range+" 本期:"+ CaculateUtils.getPercentByFloat(saleModel.getProfitRate()), obj.getString("cssweb_msg"), 0);
							}else {
								NotiUtils.showSimpleNoti(FundApplication.getInstance(), NotiIdGenerator.generate(stkcode, NotiIdGenerator.GenerFrom.REALTRADE),stkName+ "卖出下单成功"+" 价格:"+price+" 数量:"+qty , obj.getString("cssweb_msg"), 0);
							}
							//将设置中的卖出选项监听清除掉
							SelfFundSetDao.getInstance(FundApplication.getInstance()).updatePendState(stkcode, SelfFundSetModel.DONE, OperateModel.TradeType_SELL);
							//更新仓位信息
							PositionDao.getInstance(FundApplication.getInstance()).updateCurPosition(OperateModel.TradeType_SELL, qty, price);
							if (listener!=null){
								listener.orderSuccess(OperateModel.TradeType_SELL,stkcode,stkName,price,qty);
							}
						} else {
							NotiUtils.showSimpleNoti(FundApplication.getInstance(), NotiIdGenerator.generate(stkcode, NotiIdGenerator.GenerFrom.REALTRADE),stkName+ "卖出下单失败:30秒后重新下单", obj.getString("cssweb_msg"), 0);
							repeatAfterSeconds(DEFAULT_SECONDS);
							if (listener!=null){
								listener.orderFaile(OperateModel.TradeType_SELL,stkcode,stkName,price,qty,obj.getString("cssweb_msg"));
							}
						}
						FundApplication.getInstance().playSoundPool(NotiIdGenerator.GenerFrom.REALTRADE);
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}else {
					orderFaile();
					if (listener!=null){
						listener.orderFaile(OperateModel.TradeType_SELL,stkcode,stkName,price,qty,"接口访问失败");
					}
				}
			}
		};
		fundAsyTask.execute();

	}


	private void  repeatAfterSeconds(long seconds){
		maxTime --;
		if (maxTime<=0)
			return;
		new Handler().postDelayed(new Runnable() {
			@Override
			public void run() {
				saile(listener);
			}
		},seconds*1000);
	}

	private void orderFaile() {
		LogUtils.i("卖出下单失败");
		NotiUtils.showSimpleNoti(FundApplication.getInstance(), NotiIdGenerator.generate(stkcode, NotiIdGenerator.GenerFrom.REALTRADE), "卖出下单失败", "接口访问失败", 0);
		FundApplication.getInstance().playSoundPool(NotiIdGenerator.GenerFrom.REALTRADE);
	}

}
